package com.azure.bigstore.fileUpload;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;

/**
 * Created by liuhuaibin on 2018/1/26.
 */
@Service
public class UploadService {

    @Value("${file.location}")
    private String webUploadPath;

    public String upload(MultipartFile file,HttpServletRequest request) throws IOException{
        if (!file.isEmpty()) {
            if (/*file.getContentType().contains("image")*/true) {

                    // 获取图片的文件名
                    String fileName = file.getOriginalFilename();
                    // 获取图片的扩展名
                    String extensionName = StringUtils.substringAfter(fileName, ".");
                    // 新的图片文件名 = 获取时间戳+"."图片扩展名    12312153161234.jpg
                    String newFileName = String.valueOf(System.currentTimeMillis()) + "." + extensionName;
                    System.out.println("newFileName:"+newFileName);

                    //temp: upload/images/
                    String temp = "upload" + File.separator + "images" + File.separator;
                    //文件路径filePath:    D:/static/upload/images/
                    String filePath = webUploadPath.concat(temp);

                    /*ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
                    String filePath = requestAttributes.getRequest().getServletContext().getRealPath("/");
                    System.out.println("filepath:"+filePath);*/

                    //dest:   D:/static/upload/images/12312153161234.jpg
                    File dest = new File(filePath, newFileName);
                    if (!dest.getParentFile().exists()) {
                        dest.getParentFile().mkdirs();
                    }
                    // 判断是否有旧头像，如果有就先删除旧头像，再上传
                    /*SUser userInfo = sUserService.findUserInfo(userId.toString());
                    if (StringUtils.isNotBlank(userInfo.getUserHead())) {
                        String oldFilePath = webUploadPath.concat(userInfo.getUserHead());
                        File oldFile = new File(oldFilePath);
                        if (oldFile.exists()) {
                            oldFile.delete();
                        }
                    }*/

                    // 上传到指定目录
                    file.transferTo(dest);

                    // 将反斜杠转换为正斜杠
                    String dataURL = temp.replaceAll("\\\\", "/") + newFileName;
                    String serverURL = request.getScheme().toLowerCase()+"://"+request.getServerName()+":"+request.getServerPort()+"/";
                    System.out.println(serverURL);
                    return serverURL+dataURL;

            }
        }
        return "上传失败。";
    }
}
